jQuery(document).ready(function($) {

  $("[placeholder]").placeholder();

$('#post_poll_button').click(function(){

   if(atleastTwoAnswersFilledIn() && questionFilledIn()){
        //alert('post by ajax dit dat alles');
        //alert('post by ajax dit dat alles');
       postPoll();
   }
});

  $('.tab.poll input.answer').keyup(function(){
      
          if(allAnswersFilledIn()){
              addAnswerField();
          }
      })

    function allAnswersFilledIn(){
       var allAnswersFilledIn = true;
         $('.tab.poll input.answer').each(function(){
              if($(this).val() == "" || $(this).val()== $(this).attr("placeholder")){
                    allAnswersFilledIn = false;
                }
         })
         return allAnswersFilledIn;
    }



    function addAnswerField(){
        var answerField = $('.tab.poll input.answer').eq(0).clone(true);
        answerField.val("");
        answerField.insertAfter('.tab.poll input.answer:last');
        
    }

    //VALIDATION///
    function atleastTwoAnswersFilledIn(){
        var numberOfFilledInAnswers = 0;
         $('.tab.poll input.answer').each(function(){
             if($(this).val() != "" && $(this).val() != $(this).attr("placeholder")){
                  numberOfFilledInAnswers++;
             }
         });

       // alert(numberOfFilledInAnswers);
        return (numberOfFilledInAnswers > 1);
    };

    function questionFilledIn(){
        var questionField = $('#question');
         if(questionField.val() != "" && questionField.val() != questionField.attr("placeholder")){
             return true;
         }else{
             return false;
         }
    }

    //POST POLL
   function postPoll(){


       var postData = $('#poll_form').serialize();
       $.ajax({
          url: base_url + "post/post_poll",
          type: "POST",
          data: postData,
          success: function(data){

           var post = $(data);
           post.insertBefore(".item:eq(0)");
           post.hide().slideDown();
           resetPollForm();
          }

        });
       

   }

  function resetPollForm(){
      $('.tab.poll input.answer').each(function(index, value){
          if(index > 2){
              $(this).remove();
          }else{
              $(this).val("");
          }
          
      });

      $('#question').val('');
     

  }
});